from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import math
import numpy as np
import cv2
class Player(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setObjectName("Player")
        self.resize(1094, 508)
        self.gridLayout_2 = QtWidgets.QGridLayout(self)
        self.gridLayout_2.setContentsMargins(11, 11, 11, 11)
        self.gridLayout_2.setSpacing(6)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.play_button = QtWidgets.QPushButton(self)
        self.play_button.setMinimumSize(QtCore.QSize(131, 41))
        self.play_button.setObjectName("play_button")
        self.horizontalLayout.addWidget(self.play_button)
        self.start_button = QtWidgets.QPushButton(self)
        self.start_button.setMinimumSize(QtCore.QSize(131, 41))
        self.start_button.setObjectName("start_button")
        self.horizontalLayout.addWidget(self.start_button)
        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.setMinimumSize(QtCore.QSize(600, 0))
        self.lineEdit.setMaximumSize(QtCore.QSize(1000, 16777215))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.graphicsView = QtWidgets.QGraphicsView(self)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout_2.addWidget(self.graphicsView, 1, 0, 1, 1)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update_image)
        self.is_playing = False
        self.file_path = None
        self.data_file = None
        self.width = 384
        self.height = 288
        self.frame_size = self.width * self.height * 2  # 2 bytes per pixel
        self.frames_num = 0
        self.cout_frames = 0
        self.image = []
        self.retranslateUi()

    def retranslateUi(self):
        self.setWindowTitle("Play file.data")
        self.play_button.setText("Start Playing")
        self.play_button.clicked.connect(self.play_file)
        self.start_button.setText("Choose file.data")
        self.start_button.clicked.connect(self.choose_data_file)
        self.scene = QtWidgets.QGraphicsScene()

    def play_file(self):
        self.is_playing = not self.is_playing
        if self.is_playing and self.file_path:
            self.play_button.setText("Stop Playinging")
            self.data_file = open(self.file_path, 'rb')
            self.data_file.seek(0, 2)  # Move to end of file
            file_size = self.data_file.tell()
            self.data_file.seek(0)  # Move back to start
            self.frames_num = file_size // self.frame_size
            self.timer.start(20)
        elif not self.is_playing:
            self.play_button.setText("Start Recording")
            self.timer.stop()
            if self.data_file:
                self.data_file.close()
            self.data_file = None
            self.cout_frames = 0

    def choose_data_file(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.file_path, _ = QFileDialog.getOpenFileName(self, "Open .data File", "", "Data Files (*.data);;All Files (*)",
                                                   options=options)
        if self.file_path:
            self.lineEdit.setText(self.file_path)

    def update_image(self):
        if self.cout_frames >= self.frames_num:
            self.play_button.setText("Start Recording")
            self.timer.stop()
            if self.data_file:
                self.data_file.close()
            self.data_file = None
            self.cout_frames = 0
            self.is_playing = not self.is_playing
        else:
            self.data_file.seek(self.cout_frames * self.frame_size)
            self.cout_frames += 1
            frame_data = self.data_file.read(self.frame_size)
            raw_data = np.frombuffer(frame_data, dtype=np.uint16).reshape(self.height, self.width)
            image = cv2.normalize(raw_data, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
            h, w = image.shape
            q_image = QtGui.QImage(image.data, w, h, w, QtGui.QImage.Format_Grayscale8)
            item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(q_image))
            # 清空场景并添加新的 QPixmapItem
            self.scene.clear()
            self.scene.addItem(item)
            self.graphicsView.setScene(self.scene)
            self.graphicsView.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
            # self.graphicsView.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)

    def closeEvent(self, event):
        if self.data_file and not self.data_file.closed:
            self.data_file.close()
        event.accept()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Widget = Player()
    Widget.show()
    sys.exit(app.exec_())
